package org.freemarker.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.freemarker.core.model.User;
import org.freemarker.core.service.UserService;
import org.freemarker.core.validator.Validator;
import org.freemarker.web.custom.CustomHttpServlet;
import org.springframework.beans.factory.annotation.Autowired;

public class RegisterUserController extends CustomHttpServlet {


	/**
	 * 
	 */
	private static final long serialVersionUID = 4386829468065838572L;
	@Autowired
	private UserService userService;
	private Validator validator= new Validator();
	
	

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		req.getRequestDispatcher("views/login/register.ftl").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		String userName = req.getParameter("username");
		String password = req.getParameter("password");
		
		User u = new User();
		
		u.setUsername(userName);
		u.setPassword(password);
		
		List<String> errors = new ArrayList();
		try {
			errors = validator.validateUser(u);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		User u2 = new User();
			u2 = userService.getUserByUsername(u.getUsername());
			if (u2 != null)
				errors.add("Username is already taken!");
		try {
			
			if(errors.size()>0){
				req.setAttribute("errors",errors);
				req.getRequestDispatcher("views/login/register.ftl").forward(req, res);
			} else {
				userService.save(u);
				req.getRequestDispatcher("views/login/login.ftl").forward(req, res);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		

	}
}
